package cn.ssa.egweibo3.controller;

import cn.ssa.egweibo3.common.response.JsonResult;
import cn.ssa.egweibo3.common.response.StatusCode;
import cn.ssa.egweibo3.mapper.UserMapper;
import cn.ssa.egweibo3.pojo.dto.UserLoginDTO;
import cn.ssa.egweibo3.pojo.dto.UserRegDTO;
import cn.ssa.egweibo3.pojo.entity.User;
import cn.ssa.egweibo3.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired  //自动装配
    private UserMapper userMapper;
    @ApiOperation(value = "用户功能")
    @PostMapping("reg")
    public JsonResult reg(@RequestBody UserRegDTO userRegDTO) {
        log.debug("userRegDTO" + userRegDTO);
        UserVO userVO = userMapper.selectByUsername(userRegDTO.getUsername());
        if (userVO != null) {
            return new JsonResult(StatusCode.USERNAME_ALREADY_EXISTS);
        }
        //存入数据
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        userMapper.inserUser(user);
        return JsonResult.ok();//注册成功
    }
        /**
         * 2.登录功能
         */
        @ApiOperation(value = "登录功能")
        @PostMapping("login")
        public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
            System.out.println("userLoginDTO = " + userLoginDTO);
            UserVO userVO = userMapper.selectByUsername(userLoginDTO.getUsername());
            if (userVO==null){//用户名错误
                return new JsonResult(StatusCode.USERNAME_ERROR);

            }
            //比较密码
            if (userLoginDTO.getPassword().equals(userVO.getPassword())){
                session.setAttribute("user",userVO);
                return new JsonResult(StatusCode.PASSWORD_ERROR);//登录成功

            }
            return new JsonResult(StatusCode.PASSWORD_ERROR);//密码错误



        }
    /**
     * 3.获取当前用户功能
     */
    @ApiOperation(value = "获取当前用户")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");

        return JsonResult.ok(userVO);
    }

    /**
     * 4.退出登录功能
     */
    @ApiOperation(value = "退出登录")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
    }


}
